﻿using System;
using System.Linq;
using System.Net;
using System.Threading;
using System.Web;
using mojoPortal.Business;

namespace blackhouse.StareKino.Web.Navigation {
    internal class ModuleActionsHelper {

        #region Fields

        private readonly string url;
        private const string UrlQueryParameter = "onlyonce";

        #endregion

        #region Constructors

        public ModuleActionsHelper(int siteId) {
            this.url = this.GetOnlyOnceActionUrl(siteId);
        }

        #endregion

        #region Methods

        private string GetOnlyOnceActionUrl(int siteId) {
            if (HttpContext.Current == null) return String.Empty;
            var host = HttpContext.Current.Request.Url.Host;
            var ss = new SiteSettings(siteId);
            var sf = SiteFolder.GetBySite(ss.SiteGuid).FirstOrDefault();
            string folder = String.Empty;
            if (sf != null)
                folder = "/" + sf.FolderName + "/";
            return "http://" + host + folder + "?" + UrlQueryParameter + "=1";
        }

        internal void Call() {
            ThreadPool.QueueUserWorkItem(obj => {
                if (String.IsNullOrEmpty(this.url)) return;
                while (!this.InternalCall(this.url)) {
                    Thread.Sleep(TimeSpan.FromMinutes(1));
                }
            });
        }

        private bool InternalCall(string requestUrl) {
            var request = WebRequest.Create(requestUrl);
            try {
                var response = request.GetResponse() as HttpWebResponse;
                return response != null && response.StatusCode == HttpStatusCode.OK;
            } catch {
                return false;
            }
        }

        internal static bool RequestOnlyOnceAction() {
            return HttpContext.Current != null && HttpContext.Current.Request.QueryString[UrlQueryParameter] == "1";
        }

        #endregion

    }
}